package com.cardcaptorsakura.model.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.index.Indexed;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 用户偏好实体类
 * 存储用户的个性化设置、偏好配置等信息
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "user_preferences")
public class UserPreference {

    /**
     * 偏好ID
     */
    @Id
    private String id;

    /**
     * 用户ID
     */
    @Indexed(unique = true)
    private String userId;

    /**
     * 语言偏好
     */
    private LanguagePreference languagePreference;

    /**
     * 人格偏好
     */
    private PersonaPreference personaPreference;

    /**
     * 交互偏好
     */
    private InteractionPreference interactionPreference;

    /**
     * 内容偏好
     */
    private ContentPreference contentPreference;

    /**
     * 通知偏好
     */
    private NotificationPreference notificationPreference;

    /**
     * 隐私偏好
     */
    private PrivacyPreference privacyPreference;

    /**
     * 界面偏好
     */
    private UIPreference uiPreference;

    /**
     * 多媒体偏好
     */
    private MediaPreference mediaPreference;

    /**
     * 学习偏好
     */
    private LearningPreference learningPreference;

    /**
     * 创建时间
     */
    @Builder.Default
    private LocalDateTime createdAt = LocalDateTime.now();

    /**
     * 更新时间
     */
    @Builder.Default
    private LocalDateTime updatedAt = LocalDateTime.now();

    /**
     * 版本号
     */
    @Builder.Default
    private Integer version = 1;

    /**
     * 扩展属性
     */
    private Map<String, Object> metadata;

    /**
     * 语言偏好
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class LanguagePreference {
        /**
         * 主要语言
         */
        @Builder.Default
        private String primaryLanguage = "zh-CN";

        /**
         * 备用语言列表
         */
        private List<String> secondaryLanguages;

        /**
         * 自动检测语言
         */
        @Builder.Default
        private Boolean autoDetectLanguage = true;

        /**
         * 翻译偏好
         */
        @Builder.Default
        private Boolean enableTranslation = false;

        /**
         * 目标翻译语言
         */
        private String translationTargetLanguage;

        /**
         * 语言学习模式
         */
        @Builder.Default
        private Boolean languageLearningMode = false;

        /**
         * 学习目标语言
         */
        private String learningTargetLanguage;
    }

    /**
     * 人格偏好
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class PersonaPreference {
        /**
         * 默认人格ID
         */
        private String defaultPersonaId;

        /**
         * 收藏的人格ID列表
         */
        private List<String> favoritePersonaIds;

        /**
         * 禁用的人格ID列表
         */
        private List<String> disabledPersonaIds;

        /**
         * 自动切换人格
         */
        @Builder.Default
        private Boolean autoSwitchPersona = true;

        /**
         * 人格切换策略
         */
        @Builder.Default
        private String switchStrategy = "CONTEXT_BASED";

        /**
         * 人格记忆保持时间（小时）
         */
        @Builder.Default
        private Integer memoryRetentionHours = 24;

        /**
         * 允许人格学习
         */
        @Builder.Default
        private Boolean allowPersonaLearning = true;

        /**
         * 人格个性化程度（0-100）
         */
        @Builder.Default
        private Integer personalizationLevel = 70;
    }

    /**
     * 交互偏好
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class InteractionPreference {
        /**
         * 响应速度偏好
         */
        @Builder.Default
        private String responseSpeed = "NORMAL"; // FAST, NORMAL, THOUGHTFUL

        /**
         * 回复长度偏好
         */
        @Builder.Default
        private String responseLength = "MEDIUM"; // SHORT, MEDIUM, LONG, DETAILED

        /**
         * 正式程度
         */
        @Builder.Default
        private String formalityLevel = "CASUAL"; // FORMAL, SEMI_FORMAL, CASUAL, FRIENDLY

        /**
         * 情感表达程度
         */
        @Builder.Default
        private Integer emotionalExpression = 70; // 0-100

        /**
         * 幽默程度
         */
        @Builder.Default
        private Integer humorLevel = 50; // 0-100

        /**
         * 主动性程度
         */
        @Builder.Default
        private Integer proactivityLevel = 60; // 0-100

        /**
         * 启用上下文记忆
         */
        @Builder.Default
        private Boolean enableContextMemory = true;

        /**
         * 上下文记忆长度
         */
        @Builder.Default
        private Integer contextMemoryLength = 10;

        /**
         * 启用个性化建议
         */
        @Builder.Default
        private Boolean enablePersonalizedSuggestions = true;

        /**
         * 交互模式
         */
        @Builder.Default
        private String interactionMode = "CONVERSATIONAL"; // CONVERSATIONAL, TASK_ORIENTED, EDUCATIONAL
    }

    /**
     * 内容偏好
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ContentPreference {
        /**
         * 兴趣主题列表
         */
        private List<String> interestedTopics;

        /**
         * 不感兴趣主题列表
         */
        private List<String> disinterestedTopics;

        /**
         * 内容复杂度偏好
         */
        @Builder.Default
        private String complexityLevel = "INTERMEDIATE"; // BEGINNER, INTERMEDIATE, ADVANCED, EXPERT

        /**
         * 内容类型偏好
         */
        private List<String> preferredContentTypes; // TEXT, IMAGE, AUDIO, VIDEO, INTERACTIVE

        /**
         * 启用内容过滤
         */
        @Builder.Default
        private Boolean enableContentFiltering = true;

        /**
         * 内容过滤级别
         */
        @Builder.Default
        private String contentFilterLevel = "MODERATE"; // STRICT, MODERATE, RELAXED

        /**
         * 敏感内容处理
         */
        @Builder.Default
        private String sensitiveContentHandling = "WARN"; // BLOCK, WARN, ALLOW

        /**
         * 年龄适宜性检查
         */
        @Builder.Default
        private Boolean ageAppropriatenessCheck = true;

        /**
         * 用户年龄组
         */
        private String ageGroup; // CHILD, TEEN, ADULT, SENIOR
    }

    /**
     * 通知偏好
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class NotificationPreference {
        /**
         * 启用通知
         */
        @Builder.Default
        private Boolean enableNotifications = true;

        /**
         * 通知类型偏好
         */
        private Map<String, Boolean> notificationTypes;

        /**
         * 通知时间段
         */
        private List<TimeRange> allowedNotificationTimes;

        /**
         * 通知频率限制
         */
        @Builder.Default
        private Integer maxNotificationsPerHour = 5;

        /**
         * 紧急通知
         */
        @Builder.Default
        private Boolean allowUrgentNotifications = true;

        /**
         * 通知声音
         */
        @Builder.Default
        private Boolean enableNotificationSound = true;

        /**
         * 通知震动
         */
        @Builder.Default
        private Boolean enableNotificationVibration = true;

        /**
         * 免打扰模式
         */
        @Builder.Default
        private Boolean doNotDisturbMode = false;

        /**
         * 免打扰时间段
         */
        private List<TimeRange> doNotDisturbTimes;
    }

    /**
     * 隐私偏好
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class PrivacyPreference {
        /**
         * 数据收集同意
         */
        @Builder.Default
        private Boolean dataCollectionConsent = false;

        /**
         * 个性化同意
         */
        @Builder.Default
        private Boolean personalizationConsent = true;

        /**
         * 分析同意
         */
        @Builder.Default
        private Boolean analyticsConsent = false;

        /**
         * 第三方分享同意
         */
        @Builder.Default
        private Boolean thirdPartyShareConsent = false;

        /**
         * 数据保留期限（天）
         */
        @Builder.Default
        private Integer dataRetentionDays = 365;

        /**
         * 自动删除旧数据
         */
        @Builder.Default
        private Boolean autoDeleteOldData = true;

        /**
         * 匿名化数据
         */
        @Builder.Default
        private Boolean anonymizeData = true;

        /**
         * 加密敏感数据
         */
        @Builder.Default
        private Boolean encryptSensitiveData = true;

        /**
         * 隐私级别
         */
        @Builder.Default
        private String privacyLevel = "BALANCED"; // MINIMAL, BALANCED, MAXIMUM
    }

    /**
     * 界面偏好
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class UIPreference {
        /**
         * 主题
         */
        @Builder.Default
        private String theme = "AUTO"; // LIGHT, DARK, AUTO

        /**
         * 主色调
         */
        @Builder.Default
        private String primaryColor = "#1976d2";

        /**
         * 字体大小
         */
        @Builder.Default
        private String fontSize = "MEDIUM"; // SMALL, MEDIUM, LARGE, EXTRA_LARGE

        /**
         * 字体系列
         */
        @Builder.Default
        private String fontFamily = "DEFAULT";

        /**
         * 动画效果
         */
        @Builder.Default
        private Boolean enableAnimations = true;

        /**
         * 动画速度
         */
        @Builder.Default
        private String animationSpeed = "NORMAL"; // SLOW, NORMAL, FAST

        /**
         * 紧凑模式
         */
        @Builder.Default
        private Boolean compactMode = false;

        /**
         * 显示头像
         */
        @Builder.Default
        private Boolean showAvatars = true;

        /**
         * 显示时间戳
         */
        @Builder.Default
        private Boolean showTimestamps = true;

        /**
         * 布局方向
         */
        @Builder.Default
        private String layoutDirection = "LTR"; // LTR, RTL
    }

    /**
     * 多媒体偏好
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class MediaPreference {
        /**
         * 自动播放音频
         */
        @Builder.Default
        private Boolean autoPlayAudio = false;

        /**
         * 自动播放视频
         */
        @Builder.Default
        private Boolean autoPlayVideo = false;

        /**
         * 音频质量
         */
        @Builder.Default
        private String audioQuality = "STANDARD"; // LOW, STANDARD, HIGH, LOSSLESS

        /**
         * 视频质量
         */
        @Builder.Default
        private String videoQuality = "AUTO"; // LOW, STANDARD, HIGH, AUTO

        /**
         * 图像质量
         */
        @Builder.Default
        private String imageQuality = "HIGH"; // LOW, STANDARD, HIGH, ORIGINAL

        /**
         * 启用字幕
         */
        @Builder.Default
        private Boolean enableSubtitles = false;

        /**
         * 字幕语言
         */
        private String subtitleLanguage;

        /**
         * 音量级别
         */
        @Builder.Default
        private Integer volumeLevel = 70; // 0-100

        /**
         * 静音模式
         */
        @Builder.Default
        private Boolean muteMode = false;

        /**
         * 数据节省模式
         */
        @Builder.Default
        private Boolean dataSaverMode = false;
    }

    /**
     * 学习偏好
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class LearningPreference {
        /**
         * 学习风格
         */
        @Builder.Default
        private String learningStyle = "MIXED"; // VISUAL, AUDITORY, KINESTHETIC, MIXED

        /**
         * 学习速度
         */
        @Builder.Default
        private String learningPace = "NORMAL"; // SLOW, NORMAL, FAST, ADAPTIVE

        /**
         * 难度偏好
         */
        @Builder.Default
        private String difficultyPreference = "PROGRESSIVE"; // EASY, MODERATE, CHALLENGING, PROGRESSIVE

        /**
         * 反馈频率
         */
        @Builder.Default
        private String feedbackFrequency = "REGULAR"; // MINIMAL, REGULAR, FREQUENT, IMMEDIATE

        /**
         * 启用自适应学习
         */
        @Builder.Default
        private Boolean enableAdaptiveLearning = true;

        /**
         * 学习目标
         */
        private List<String> learningGoals;

        /**
         * 学习时间偏好
         */
        private List<TimeRange> preferredLearningTimes;

        /**
         * 学习会话长度（分钟）
         */
        @Builder.Default
        private Integer sessionLengthMinutes = 30;

        /**
         * 启用进度跟踪
         */
        @Builder.Default
        private Boolean enableProgressTracking = true;

        /**
         * 启用成就系统
         */
        @Builder.Default
        private Boolean enableAchievements = true;
    }

    /**
     * 时间范围
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class TimeRange {
        /**
         * 开始时间（HH:mm格式）
         */
        private String startTime;

        /**
         * 结束时间（HH:mm格式）
         */
        private String endTime;

        /**
         * 星期几（1-7，1为周一）
         */
        private List<Integer> daysOfWeek;

        /**
         * 时区
         */
        private String timezone;
    }

    /**
     * 更新偏好设置
     */
    public void updatePreference(String category, Object preference) {
        switch (category.toLowerCase()) {
            case "language":
                this.languagePreference = (LanguagePreference) preference;
                break;
            case "persona":
                this.personaPreference = (PersonaPreference) preference;
                break;
            case "interaction":
                this.interactionPreference = (InteractionPreference) preference;
                break;
            case "content":
                this.contentPreference = (ContentPreference) preference;
                break;
            case "notification":
                this.notificationPreference = (NotificationPreference) preference;
                break;
            case "privacy":
                this.privacyPreference = (PrivacyPreference) preference;
                break;
            case "ui":
                this.uiPreference = (UIPreference) preference;
                break;
            case "media":
                this.mediaPreference = (MediaPreference) preference;
                break;
            case "learning":
                this.learningPreference = (LearningPreference) preference;
                break;
        }
        this.updatedAt = LocalDateTime.now();
        this.version++;
    }

    /**
     * 获取偏好设置
     */
    public Object getPreference(String category) {
        switch (category.toLowerCase()) {
            case "language":
                return this.languagePreference;
            case "persona":
                return this.personaPreference;
            case "interaction":
                return this.interactionPreference;
            case "content":
                return this.contentPreference;
            case "notification":
                return this.notificationPreference;
            case "privacy":
                return this.privacyPreference;
            case "ui":
                return this.uiPreference;
            case "media":
                return this.mediaPreference;
            case "learning":
                return this.learningPreference;
            default:
                return null;
        }
    }

    /**
     * 检查是否允许通知
     */
    public boolean isNotificationAllowed(String notificationType, LocalDateTime time) {
        if (notificationPreference == null || !notificationPreference.enableNotifications) {
            return false;
        }

        // 检查免打扰模式
        if (notificationPreference.doNotDisturbMode) {
            return false;
        }

        // 检查通知类型
        if (notificationPreference.notificationTypes != null) {
            Boolean typeAllowed = notificationPreference.notificationTypes.get(notificationType);
            if (typeAllowed != null && !typeAllowed) {
                return false;
            }
        }

        // 检查时间范围
        if (notificationPreference.allowedNotificationTimes != null) {
            return isTimeInRanges(time, notificationPreference.allowedNotificationTimes);
        }

        return true;
    }

    /**
     * 检查时间是否在指定范围内
     */
    private boolean isTimeInRanges(LocalDateTime time, List<TimeRange> ranges) {
        if (ranges == null || ranges.isEmpty()) {
            return true;
        }

        for (TimeRange range : ranges) {
            if (isTimeInRange(time, range)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查时间是否在指定范围内
     */
    private boolean isTimeInRange(LocalDateTime time, TimeRange range) {
        // 简化实现，实际应该考虑时区转换
        int dayOfWeek = time.getDayOfWeek().getValue();
        if (range.daysOfWeek != null && !range.daysOfWeek.contains(dayOfWeek)) {
            return false;
        }

        // 检查时间范围（简化实现）
        String currentTime = String.format("%02d:%02d", time.getHour(), time.getMinute());
        return currentTime.compareTo(range.startTime) >= 0 && currentTime.compareTo(range.endTime) <= 0;
    }

    /**
     * 获取内容过滤级别数值
     */
    public int getContentFilterLevelValue() {
        if (contentPreference == null || contentPreference.contentFilterLevel == null) {
            return 2; // MODERATE
        }

        switch (contentPreference.contentFilterLevel.toUpperCase()) {
            case "STRICT":
                return 3;
            case "MODERATE":
                return 2;
            case "RELAXED":
                return 1;
            default:
                return 2;
        }
    }

    /**
     * 检查是否启用了特定功能
     */
    public boolean isFeatureEnabled(String feature) {
        switch (feature.toLowerCase()) {
            case "context_memory":
                return interactionPreference != null && interactionPreference.enableContextMemory;
            case "personalized_suggestions":
                return interactionPreference != null && interactionPreference.enablePersonalizedSuggestions;
            case "content_filtering":
                return contentPreference != null && contentPreference.enableContentFiltering;
            case "auto_switch_persona":
                return personaPreference != null && personaPreference.autoSwitchPersona;
            case "persona_learning":
                return personaPreference != null && personaPreference.allowPersonaLearning;
            case "adaptive_learning":
                return learningPreference != null && learningPreference.enableAdaptiveLearning;
            case "progress_tracking":
                return learningPreference != null && learningPreference.enableProgressTracking;
            case "achievements":
                return learningPreference != null && learningPreference.enableAchievements;
            default:
                return false;
        }
    }

    /**
     * 重置为默认设置
     */
    public void resetToDefaults() {
        this.languagePreference = LanguagePreference.builder().build();
        this.personaPreference = PersonaPreference.builder().build();
        this.interactionPreference = InteractionPreference.builder().build();
        this.contentPreference = ContentPreference.builder().build();
        this.notificationPreference = NotificationPreference.builder().build();
        this.privacyPreference = PrivacyPreference.builder().build();
        this.uiPreference = UIPreference.builder().build();
        this.mediaPreference = MediaPreference.builder().build();
        this.learningPreference = LearningPreference.builder().build();
        this.updatedAt = LocalDateTime.now();
        this.version++;
    }
}